#region using

using System.IO;
using DataStubGenerator.Exceptions;
using Lib.Dialogs;
using Lib.Properties;
using Lib.Views;

#endregion


namespace DataStubGenerator
{
    public class MainViewPresenter  {
        #region Fields/const

        private readonly IMainView _view;
        private readonly FileModel _model;

        #endregion
        #region Constructor

        public MainViewPresenter(IMainView view, FileModel model)
        {
            _view = view;
            _model = model;

            _view.RunSql += delegate { RunSql(); };
            _view.SaveTable += delegate { SaveTableToFile(); };
            _view.LoadTableFromFile += delegate { LoadTableFromFile(); };
            _view.GenerateCode += delegate { GenerateCode(); };
        }

        public IMainView View
        {
            get { return _view; }
        }



        #endregion
        #region IMainView Event Handlers

        public void LoadTableFromFile()
        {
            if (_model.LoadFile(_view.GetOpenFileName())) 
                _view.Table = _model.Table;
        }

        public void SaveTableToFile()
        {
            if (_model.Table == null)
                throw new LoggableException(true,"Data not initialized","Save Failed");

            string tmpFileName = _view.GetSaveFileName();

            if(tmpFileName==null)
                return;

            if (!tmpFileName.ToLower().EndsWith(Resources.Xtbl)) 
                throw new SaveFailedException(true);

            _model.SaveFile(tmpFileName);
        }

        public void RunSql()
        {
            _model.CreateTableFromSql(_view.SqlText);
            _view.Table = _model.Table;
        }

        public void GenerateCode()
        {
            if(_model.Table == null) return;
            //TODO I will need to refactor this
            GenerateStubCodeCommand cmd = new GenerateStubCodeCommand(_model.Table); 
            StringWriter sw = new StringWriter();
            cmd.Execute(sw);

            CodeDialog dlg = new CodeDialog();
            dlg.Code.Text = sw.ToString();
            dlg.ShowDialog();
        }

        #endregion
    }
}
